package com.dmcloud.zuul.filter;

import com.dmcloud.zuul.filter.abstractzuul.AbstractPreZuulFilter;
import com.dmcloud.zuul.filter.pojo.TokenInfo;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by xiaodao
 * date: 2019/11/7
 * 废弃.
 */
//@Component
@Slf4j
public class AuthorizationFilter extends AbstractPreZuulFilter {

    @Override
    public int filterOrder() {
        return 3;
    }


    @Override
    protected Object cRun() {
        log.info("认证开始");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        if(isNeedAuth(request)){
            TokenInfo tokenInfo = (TokenInfo)request.getAttribute("tokenInfo");
            //这个是失效了.active
            if(tokenInfo!=null && tokenInfo.isActive()){
                if(!hasPermission(tokenInfo, request)) {
                    log.info("audit log update fail 403");
                    fail(403, "权限认证失败");
                }
                //有权限了这里放入header中
                requestContext.addZuulRequestHeader("username", tokenInfo.getUser_name());
            }else {
                if(!StringUtils.startsWith(request.getRequestURI(), "/token")) {
                    log.info("audit log update fail 401");
//                    handleError(401, requestContext);
                    fail(401,"认证失败");
                }
            }
        }
        log.info("认证结束-可以通过");
        return success();
    }


    private boolean hasPermission(TokenInfo tokenInfo, HttpServletRequest request) {
        return  true;
    }
    private boolean isNeedAuth(HttpServletRequest request) {
        return true;
    }
    private void handleError(int status, RequestContext requestContext) {
        requestContext.getResponse().setContentType("application/json");
        requestContext.setResponseStatusCode(status);

        requestContext.setResponseBody("{\"message\":\"auth fail\"}");
//        requestContext.setResponseBody( ResultMessage.failed("认证失败").toString());
        requestContext.setSendZuulResponse(false);
    }
}
